package com.shijie.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tk.mybatis.mapper.entity.Example;

import com.shijie.core.AbstractService;
import com.shijie.domain.entity.Categories;
import com.shijie.domain.enums.EnumInterface;
import com.shijie.mapper.CategoriesMapper;
import com.shijie.utils.TreeUtil;

/*
 *  @author: smart boy
 *  @date: 2018-08-06
 */
@Service
public class CategoriesService extends AbstractService<Categories> {

	@Resource
	private CategoriesMapper categoriesMapper;
	
	public List<Categories> selectCategoriesByType(String type, String status) {

		Example con = new Example(Categories.class);
		Example.Criteria criteria = con.createCriteria();
		criteria.andEqualTo("type", type);
		if (StringUtils.isNotBlank(status)) {
			criteria.andEqualTo("status", status);
		}
		con.orderBy("rank").asc().orderBy("sort").asc();
		List<Categories> categories = categoriesMapper.selectByCondition(con);
		return TreeUtil.tree(categories);
	}

	public List<Categories> selectByParentId(Integer parentId,String type, Integer status) {

		Example con = new Example(Categories.class);
		Example.Criteria criteria = con.createCriteria();
		criteria.andEqualTo("parentId", parentId);
        criteria.andEqualTo("type", type);
        if (status != null) {
            criteria.andEqualTo("status", status);
        }
        con.orderBy("rank").asc().orderBy("sort").asc();
		List<Categories> categories = categoriesMapper.selectByCondition(con);
		return categories;
	}

	@Transactional
	public void save(Categories categories){
		if(categories.getId() == null){
			Categories parent = categoriesMapper.selectByPrimaryKey(categories.getParentId());
			categoriesMapper.insert(categories);
			Categories category = new Categories();
			category.setPath(parent.getPath()+categories.getId()+"/");
			category.setId(categories.getId());
			categoriesMapper.updateByPrimaryKeySelective(category);
			
		}else{
			Categories parent = categoriesMapper.selectByPrimaryKey(categories.getParentId());
			categories.setPath(parent.getPath()+categories.getId()+"/");
			categoriesMapper.updateByPrimaryKey(categories);
		}
	}
	
	public void delete(int id){
		Categories c = new Categories();
		c.setId(id);
		c.setStatus(EnumInterface.Status.INVALID.ordinal());
		categoriesMapper.updateByPrimaryKeySelective(c);
	}
}
